<?php

namespace controller;

use Exception;
use Util;
use ZipArchive;
use Twig\Loader\FilesystemLoader;
use Twig\Environment;
class Index
{
    public function index()
    {
        global $key;
        global $websites;
        global $user;
        global $templateData;
        if (!empty($_POST) && count($_POST) > 0) {
            $pathId = $_POST['path-id'] ?? '';
            $file = $_FILES['zip'] && $_FILES['zip']['error'] == 0 ? [
                'name' => $_FILES['zip']['name'],
                'tmp_name' => $_FILES['zip']['tmp_name']
            ] : null;
            $password = $_POST['password'] ?? '';
            if (empty($pathId) || empty($file)) {
                msg(-1, '参数不完整', $_FILES['zip']);
            }
            if (empty($_SESSION['u']) && $password != $key) {
                msg(-1, '密码不正确');
            }
            $_SESSION['u'] = 1;
            $path = Util::arrayFind($pathId, $websites, 'id', 'path');
            if (!$path) {
                msg(-1, '站点路径不存在');
            }
            try {
                if (!is_dir($path)) {
                    msg(-1, '这个站点路径不存在');
                }
                $oldPath = $file['tmp_name'];
//                 $newPath = $path . '/' . $file['name'];
                $extension = pathinfo($file['name'])['extension'];
                $fileName = time().'.'.$extension;
                $newPath = $path . '/' .$fileName;
                $res = move_uploaded_file($oldPath, $newPath);
                $zip = new ZipArchive;
                $res = $zip->open($newPath);
                if ($res === true) {
                    Util::del($path, [$fileName]);
                    $zip->extractTo($path);
                    $zip->close();
                    $_SESSION['path_id'] = $pathId;
                    msg(1, '上传成功');
                } else {
                    msg(-1, Util::ZipStatusString($res));
                }
            } catch (Exception $e) {
                msg(-1, $e->getMessage());
            }
        }
        $loader = new FilesystemLoader(BASE_PATH . '/view/');
        $twig = new Environment($loader);
        $template = $twig->load('index.twig');
        $data = array_merge($templateData, []);
        echo $template->render($data);
    }
}